package com.iflytek.cosmo.ocr.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.iflytek.cosmo.ocr.common.config.ArgusProperties;
import com.iflytek.cosmo.ocr.model.domain.LogBatchParam;
import com.iflytek.cosmo.ocr.model.domain.LogParam;
import com.iflytek.cosmo.ocr.service.ArgusPostService;
import com.iflytek.cosmo.ocr.support.mq.Provider;
import com.iflytek.crius.agent.factory.MetaFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 数据埋点实现
 * @author admin
 */
@Service
public class ArgusPostServiceImpl implements ArgusPostService {

    /**
     * Logger
     */
    private Logger logger = LoggerFactory.getLogger(ArgusPostServiceImpl.class);

    /**
     * iflybar argus
     */
    @Value("${iflybar.mq.argus}")
    private String iflybarArgusQueue;

    /**
     * ArgusProperties
     */
    @Autowired
    private ArgusProperties argusProperties;

    /**
     * Provider
     */
    @Autowired
    private Provider provider;

    private final String SEND_TYPE_DETAIL = "detail";

    private final String SEND_TYPE_IP = "ip";

    /**
     * 指标名称前缀
     */
    private final String BUSINESS_BIZ_REAL_IPART = "business.biz.real.ipart.";

    /**
     * 数据埋点通用方法
     *
     * @param clientIp 客户端IP
     * @param metric   指标名称
     * @param value    指标值
     * @param tags     tags
     * @param sendType ip/detail
     */
    @Override
    public void postAgent(String clientIp, String metric, Object value, String tags, String sendType) {
        try {
            if (!argusProperties.getBuryingEnable()) {
                return;
            }
            if (sendType == null) {
                sendType = argusProperties.getSendType();
            }
            MetaFactory factory = new MetaFactory();
            String message = "";
            try {
                switch (sendType) {
                    case SEND_TYPE_DETAIL:
                        message = factory.productDetailMeta(argusProperties.getAreaCode(), argusProperties.getOrgCode(), metric, value, 0L, tags);
                        break;
                    case SEND_TYPE_IP:
                        message = factory.productMetaData(clientIp, metric, value, 0L, tags);
                        break;
                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (StringUtils.isEmpty(message)) {
                return;
            }
            Map<String, String> map = new HashMap<String, String>();
            map.put("type", sendType);
            map.put("ip", clientIp);
            map.put("value", message);
            provider.send(iflybarArgusQueue, JSONObject.toJSONString(map));
            logger.info("发送埋点数据：{}", message);
        }
        catch (Exception e) {
            logger.warn("埋点异常, clientIp: {}, metric: {}, value: {}, tags: {}, sendType: {}", clientIp, metric, value,
                    tags, sendType, e);
        }
    }

    /**
     * 调用数据分析平台接口方法
     * @param type 统计的指标类型
     * @param value 指标的数值（时长，次数等）
     * @param userId 用户id
     * @param userIp ip地址
     */
    @Override
    public void addToolLog(String type, Object value, String userId, String userIp, String mac) {

        // 埋点开关
        if (!argusProperties.getBuryingEnable()) {
            return;
        }
        String sendType = argusProperties.getSendType();
        String areaCode = argusProperties.getAreaCode();
        String orgCode = argusProperties.getOrgCode();
        String metric = BUSINESS_BIZ_REAL_IPART + type;
        //String tags = getTags(userId, userIp, mac);
        String tags = String.format("account=%s,name=%s,ip=%s,mac=%s", userId, userId, userIp, mac);
        postAgent(sendType,areaCode, userIp, orgCode, metric, value, tags, "");
    }

    @Override
    public void addToolLog(List<LogParam> logParamList, String userIp) {

    }

    @Override
    public void addBatchToolLog(LogBatchParam logBatchParam, String userIp) {

    }

    @Override
    public void postAgent(String sendType, String areaCode, String userIp, String org, String metric, Object obj, String tags, String computerName) {

    }


}
